package com.vonchange.headb.utils.orm.impl;

import com.vonchange.headb.core.constant.HeaConstant;
import com.vonchange.headb.core.exception.NotAllowDBColumnException;
import com.vonchange.headb.utils.orm.IOrm;
import com.vonchange.headb.utils.string.HStringUtils;

public class OrmImpl implements IOrm {

	/**
	 * 数据库字段名转实体类字段名
	 * 
	 * @param colName
	 * @return 实体类字段名
	 */
	@Override
	public  String toFiled(String colName) {
		StringBuffer sb = new StringBuffer();
		boolean flag = false;
		for (int i = 0; i < colName.length(); i++) {
			char cur = colName.charAt(i);
			if (cur == '_') {
				flag = true;

			} else {
				if (flag) {
					sb.append(Character.toUpperCase(cur));
					flag = false;
				} else {
					//sb.append(cur);
					sb.append(Character.toLowerCase(cur));
				}
			}
		}
		return HStringUtils.replaceEach(sb.toString(), HeaConstant.CharToNum.NUM, HeaConstant.CharToNum.CHAR);
	}

	@Override
	public String toSql(String myHql) {
		StringBuffer sb = new StringBuffer();
		boolean flag = false;
		boolean isLetter = false;
		for (int i = 0; i < myHql.length(); i++) {
			char cur = myHql.charAt(i);
			if (cur == '_') {
				throw new NotAllowDBColumnException("不允许使用数据库字段  _ !");
			}
			if (cur == ':') {
				flag = true;
			}
			if (cur != ':' && !Character.isLetter(cur)) {
				flag = false;
			}
			if (flag) {
				sb.append(cur);
				continue;
			}
			if (Character.isUpperCase(cur) && isLetter) {
				sb.append("_");
				sb.append(Character.toLowerCase(cur));
			} else {
				sb.append(Character.toLowerCase(cur));
			}
			if (!Character.isLetter(cur)) {
				isLetter = false;
			} else {
				isLetter = true;
			}
		}
		return HStringUtils.replaceEach(sb.toString(), HeaConstant.CharToNum.CHAR, HeaConstant.CharToNum.NUM);
	}

}
